package eerbaar.v2.app.strategy;

import eerbaar.client.ctr.IGameController;
import eerbaar.client.ctr.IGameControllerFactory;
import eerbaar.game.IGame;
import eerbaar.persona.IPersona;
import eerbaar.position.IPosition;
import eerbaar.position.PositionFactory;
import eerbaar.position.WrongPositionException;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.v2.app.mover.IPersonaMover;

public class GoToStrategy implements IPersonaStrategy {

    private final int gotoX;

    private final int gotoY;

    private final IPersona subject;

    public GoToStrategy(IPersona subject, int gotoX, int gotoY) {
        this.gotoX = gotoX;
        this.gotoY = gotoY;
        this.subject = subject;
    }

    private String findNewPosition(IPosition source, IPosition destination) {

        String result = null;

        final int sourceX = source.getX();
        final int sourceY = source.getY();
        int destinationX = destination.getX();
        int destinationY = destination.getY();

        int newX = sourceX;
        int newY = sourceY;

        if (newX < destinationX) {
            result = ":incrementx";
        } else if (newX > destinationX) {
            result = ":decrementx";
        } else if (newY < destinationY) {
            result = ":incrementy";
        } else if (newY > destinationY) {
            result = ":decrementy";
        }

        return result;
    }

    @Override
    public boolean move(IPersonaMover controller, IGame game)
            throws WrongPositionException {

        boolean result = false;

        IPosition destination = PositionFactory.createPosition(this.gotoX,
                this.gotoY);

        IPersona persona = this.subject;
        IPosition source = persona.getPosition();

        String command = findNewPosition(source, destination);

        if (command != null) {

            IGameControllerFactory factory = ServiceFactory
                    .getService(IGameControllerFactory.class);
            IGameController gameController = factory.create(this.subject, game);

            result = gameController.input(command);
        }

        if (this.subject.getName().equals("pet")) {
            StrategyUtil.clearValueArea();
        }

        return result;
    }

}
